/*
* $Id: CommonFunction.cpp 29 2010-02-16 20:37:15Z volok-aleksej@yandex.ru $
*
* Copyright 2008 by Volokitin Alexey
* All rights reserved
*
*/
#include "../include.h"
#include "CommonFunction.h"
#include <shlwapi.h>
#include <pcre.h>

CFont* CCommonFunction::GetFont(const std::tstring& strFontName, int sizeFont, bool bBold, bool bItalic, bool bUnderLine){
	LOGFONT lf;
	memset(&lf, 0, sizeof(lf));
	lf.lfHeight = sizeFont;
	lf.lfWeight = bBold ? FW_BOLD : FW_NORMAL;
	lf.lfCharSet = ANSI_CHARSET;
	lf.lfItalic = bItalic;
	lf.lfUnderline = bUnderLine;
	_tcscpy_s(lf.lfFaceName, LF_FACESIZE, strFontName.c_str());
	CFont* font = new CFont();
	font->CreateFontIndirect(&lf);
	return font;
}

COLORREF CCommonFunction::GetBeeColor(){
	return RGB(221, 165, 54);
}

std::tstring CCommonFunction::GetRegValue(const std::tstring& strNameKey, const std::tstring& strNameValue){
	std::tstring strValue;
	HKEY key;
	BOOL bRes = RegOpenKeyEx(HKEY_CURRENT_USER, strNameKey.c_str(), 0, KEY_QUERY_VALUE, &key);
	if(bRes == ERROR_SUCCESS){
		DWORD    cValues;
		RegQueryInfoKey(key, NULL, NULL, NULL, NULL, NULL, NULL, &cValues, NULL, NULL, NULL, NULL);
		DWORD    cchMaxValue;
		DWORD    cbMaxValueData;
		for (DWORD i = 0; i <= cValues; i++){
			cchMaxValue = 255;
			cbMaxValueData = 16383;
			TCHAR* value = new TCHAR[cbMaxValueData];
			TCHAR* valueName = new TCHAR[cchMaxValue];
			memset(value, 0, cbMaxValueData * sizeof(TCHAR));
			memset(valueName, 0, cchMaxValue * sizeof(TCHAR));
			int nres = RegEnumValue(key, i, valueName, &cchMaxValue, NULL, NULL, (LPBYTE)value, &cbMaxValueData);
			if(strNameValue == valueName)
				strValue = value;
			delete value;
			delete valueName;
		}
	}
	RegCloseKey(key);
	return strValue;
}

void CCommonFunction::SetRegValue(const std::tstring& strNameKey, const std::tstring& strNameValue, const std::tstring& strValue){
	HKEY key;
	BOOL bRes = RegOpenKeyEx(HKEY_CURRENT_USER, strNameKey.c_str(), 0, KEY_WRITE, &key);
	if(bRes != ERROR_SUCCESS){
		DWORD nDispos;
		RegCreateKeyEx(HKEY_CURRENT_USER, strNameKey.c_str(), NULL, NULL,
			REG_OPTION_NON_VOLATILE, KEY_CREATE_SUB_KEY | KEY_WRITE, NULL, &key, &nDispos);
	}
	RegSetValueEx(key, strNameValue.c_str(), NULL, REG_SZ, (LPBYTE)strValue.c_str(), DWORD(strValue.size() * sizeof(TCHAR)));
	RegCloseKey(key);
}

bool CCommonFunction::ValidRegex(const std::tstring& strValue, const std::tstring& strRegex){
	USES_CONVERSION;
	pcre *re;
	const char *error;
	int erroffset;
	re  =  pcre_compile(T2A(strRegex.c_str()), 0, &error, &erroffset, NULL);
	if(!re){
		return false;}
	else
	{
		int ovector[2];
		int count = pcre_exec(re,  NULL, (char *)T2A(strValue.c_str()), (int)strValue.size(), 0, 0, ovector, 2);
		if(count != 1 || ovector[0] != 0 || ovector[1] != strValue.size() || strValue.empty()){
			return false;}
	}
	return true;
}